﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;

namespace WPFSample.PrintBannerSample
{
    class BannerDocumentPaginator : DocumentPaginator
    {
        Size sizePage;
        Size sizeMax = new Size(0, 0);

        private string txt;

        public string Text
        {
            get { return txt; }
            set { txt = value; }
        }

        private Typeface face = new Typeface("宋体");

        public Typeface Typeface
        {
            get { return face; }
            set { face = value; }
        }

        FormattedText GetFormattedText(char ch, Typeface face, double em)
        {
            return new FormattedText(ch.ToString(), CultureInfo.CurrentCulture, FlowDirection.LeftToRight, face, em, Brushes.Black);
        }

        public override bool IsPageCountValid
        {
            get
            {
                foreach (char ch in this.txt)
                {
                    FormattedText formtxt = this.GetFormattedText(ch, face, 100);
                    this.sizeMax.Width = Math.Max(this.sizeMax.Width, formtxt.Width);
                    this.sizeMax.Height = Math.Max(this.sizeMax.Height, formtxt.Height);
                }

                return true;
            }
        }

        public override int PageCount
        {
            get
            {
                return this.txt == null ? 0 : this.txt.Length;
            }
        }

        public override Size PageSize
        {
            get
            {
                return this.sizePage;
            }

            set
            {
                this.sizePage = value;
            }
        }

        public override IDocumentPaginatorSource Source
        {
            get
            {
                return null;
            }
        }

        public override DocumentPage GetPage(int pageNumber)
        {
            DrawingVisual vis = new DrawingVisual();
            DrawingContext dc = vis.RenderOpen();

            double factor = Math.Min((this.PageSize.Width - 5) / this.sizeMax.Width, (this.PageSize.Height - 5) / this.sizeMax.Height);

            FormattedText formtxt = this.GetFormattedText(this.txt[pageNumber], this.face, factor * 100);
            Point ptText = new Point((this.PageSize.Width - formtxt.Width) / 2, (this.PageSize.Height - formtxt.Height) / 2);
            dc.DrawText(formtxt, ptText);
            dc.Close();
            return new DocumentPage(vis);
        }
    }
}
